﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VehicleManagement.Models;
using VehicleManagement.Codes;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;
using VehicleManagement.ControllersServices;
using System.Collections;
using System.IO;



namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "管理员,财务人员")]
    public class FinanManInfoController : Controller
    {
        const int PAGE_MAX = 8;

        FinanManInfoServices finanmaninfoservices = new FinanManInfoServices();
        // GET: /FinanManInfo/

        public ActionResult Index()
        {
            Hashtable ht = new Hashtable();
            SearchFinanManByRequeast(ref ht);
            int page;
            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
                page = int.Parse(Request.Params["Page"]);
            else
                page = 1;

            if (Session["CompanyName"] == null)
            {
                return View("../Home/Login");
            }
            
            return View(finanmaninfoservices.GetAllFinanManInfo(ht,(page - 1) * PAGE_MAX, PAGE_MAX));
        }

        //
        // GET: /FinanManInfo/MyInformation

        /// <summary>
        /// 获取财务人员信息(如财务人员个人中心)
        /// </summary>
        /// <param name="id">财务人员ID</param>
        /// <returns></returns>
        [CustomerAuthorize(Roles = "财务人员")]
        public ActionResult MyInformation()
        {
            if (Session["UserID"] == null)
                Response.Redirect("/Home/Login");
            int id = Convert.ToInt32(Session["UserID"]);

            if (Session["CompanyName"] == null)
            {
                return View("../Home/Login");
            }

            Hashtable ht = new Hashtable();
            ht.Add("companyName", Session["CompanyName"].ToString());
            ht.Add("id", id);

            return View(finanmaninfoservices.GetFinanManInfo(ht));
        }

        [HttpPost, CustomerAuthorize(Roles = "财务人员")]
        public ActionResult MyInformation(FinanManInfo FinanMan)
        {
            if (ModelState.IsValid)
            {
                int rows = finanmaninfoservices.UpDate(FinanMan);
                if (rows == 1)
                    RedirectToAction("MyInformation");
            }

            return View(FinanMan);

        }

        //
        // GET: /FinanManInfo/GetFinanManInfo/1

        /// <summary>
        /// 获取财务人员信息
        /// </summary>
        /// <param name="id">财务人员ID</param>
        /// <returns></returns>
        public ActionResult Details(int id)
        {
            Hashtable ht = new Hashtable();
            if (Session["CompanyName"] == null)
            {
                return View("../Home/Login");
            }
            ht.Add("companyName", Session["CompanyName"].ToString());
            ht.Add("id",id);
            return View(finanmaninfoservices.GetFinanManInfo(ht));
        }

        /// <summary>
        /// 添加财务人员
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            return View();

        }
        [HttpPost]
        public ActionResult Create(FinanManInfo FinanMan)
        {
            if (Session["CompanyName"] == null)
            {
                return View("../Home/Login");
            }
            FinanMan.CompanyName = Session["CompanyName"].ToString();
            if (ModelState.IsValid)
            {
                Object thisLock = new Object();
                int id = 0;
                lock (thisLock)
                {
                    finanmaninfoservices.AddFinanMan(FinanMan);
                    id = (int)SqlMapperManager.Instance.Get().QueryForObject("SELECT_FINANCIAL_IDENTITY", null);
                }
                HttpPostedFileBase file = Request.Files["file"];
                if (file != null && file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/Financial") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_FINANCIAL_HEAD_IMAGE",
                        new
                        {
                            FinanManID = id,
                            Image = id + fileExt
                        });
                }
                return RedirectToAction("Index");
            }
            else
                return View(FinanMan);
        }


        /// <summary>
        /// 财务人员信息修改
        /// </summary>
        /// <param name="id">财务人员ID</param>
        /// <param name="driveriofo">返回财务人员类</param>
        /// <returns>修改财务人员的视图</returns>
        public ActionResult Edit(int id, FinanManInfo finanmaniofo = null)
        {

            if (Request.RequestType.ToUpper().Equals("POST") && finanmaniofo != null)
            {
                finanmaninfoservices.UpDate(finanmaniofo);
                HttpPostedFileBase file = Request.Files["file"];
                if (file != null && file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/Financial") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_FINANCIAL_HEAD_IMAGE",
                        new
                        {
                            FinanManID = id,
                            Image = id + fileExt
                        });
                }
                return RedirectToAction("Index");
            }
            else
            {
                Hashtable ht = new Hashtable();
                if (Session["CompanyName"] == null)
                {
                    return View("../Home/Login");
                }
                ht.Add("companyName", Session["CompanyName"].ToString());
                ht.Add("id", id);
                finanmaniofo = finanmaninfoservices.ShowEdit(ht);
                return View(finanmaniofo);
            }

        }


        /// <summary>
        /// 财务人员删除
        /// </summary>
        /// <param name="id">财务人员ID</param>
        /// <returns>修改财务人员的视图</returns>
        [HttpPost, ActionName("DeleteFinanMan")]
        public ActionResult DeleteConfirmed(int id)
        {

            int i = finanmaninfoservices.DeleteFinan(id);
            if (i == 1)//删除成功
            {
                return Json(new { Result = "true", Message = "删除成功" });
            }
            else//删除不成功
            {
                return Json(new { Result = "false", Message = "删除失败" });
            }
          //  return RedirectToAction("Index");
        }

        //   验证email是否存在
        #region
        /// <summary>
        /// 验证email的存在
        /// </summary>
        /// 
        // POST: /FinanManInfo/CheckFinanManInfoEmail
        [HttpPost, ActionName("CheckFinanManInfoEmail")]
        public ActionResult CheckFinanManInfoEmail(string Email)
        {

            Object obj = SqlMapperManager.Instance.Get().QueryForObject("SEARCH_EMAIL", Email);

            if (obj != null)
            {
                return Json(new { Result = "true", Message = "存在此邮箱" });
            }
            else//删除不成功
            {
                return Json(new { Result = "false", Message = "暂时不存在此邮箱" });
            }
        }

        #endregion

        //验证用户登录名是否存在
        #region
        /// <summary>
        /// 验证用户登录名的存在
        /// </summary>
        /// 
        // POST: /FinanManInfo/CheckLoginName
        [HttpPost, ActionName("CheckLoginName")]
        public ActionResult CheckLoginName(string LoginName)
        {

            Object obj = SqlMapperManager.Instance.Get().QueryForObject("SEARCH_LOGINNAME", LoginName);

            if (obj != null)
            {
                return Json(new { Result = "true", Message = "存在此用户名" });
            }
            else//删除不成功
            {
                return Json(new { Result = "false", Message = "暂时不存在此用户名" });
            }
        }

        #endregion



        [ActionName("GetPagingInfo"),HttpGet]
        public ActionResult GetPagingInfo()
        {
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);

            Hashtable ht = new Hashtable();
            SearchFinanManByRequeast(ref ht);
            int itemCount = finanmaninfoservices.CountAllFinanmaninfo(ht);
            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            },JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        public void SearchFinanManByRequeast(ref Hashtable ht)
        {
            string FinFinanMan_name = Request.Params["FinanMan_name"];
            string FinSex = Request.Params["Sex"];
            string FinTelephone = Request.Params["Telephone"];

            string FinanMan_nameForSearch = "%%";
            string SexForSearch = "%%";
            string TelephoneForSearch = "%%";


            if (!string.IsNullOrEmpty(FinFinanMan_name) && FinFinanMan_name != "姓名")
                FinanMan_nameForSearch = string.Format("%{0}%", FinFinanMan_name);
            if (!string.IsNullOrEmpty(FinSex) && FinSex != "性别")
                SexForSearch = string.Format("%{0}%", FinSex);
            if (!string.IsNullOrEmpty(FinTelephone) && FinTelephone != "电话")
                TelephoneForSearch = string.Format("%{0}%", FinTelephone);

            ht.Add("FinanMan_nameForSearch", FinanMan_nameForSearch);
            ht.Add("SexForSearch", SexForSearch);
            ht.Add("TelephoneForSearch", TelephoneForSearch);
            ht.Add("companyName", Session["CompanyName"].ToString());

        }
    }
}
